#!/usr/local/bin/python3
import os

__author__ = '曹植'

from sql.app_distribution_sql import BaseSql
from urllib.request import urlretrieve
from pymysql import IntegrityError
import requests
from app_distribution import settings

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/62.0.3202.94 Safari/537.36"
}


def read_file():
    bs = BaseSql()
    sql = "SELECT filename,path FROM app_distribution_platform_fileupload"
    try:
        bs.cursor.execute(sql)
    except IntegrityError:
        pass
    bs.conn.commit()
    records = bs.cursor.fetchall()
    bs.close()
    return records


def read_path(filename):
    bs = BaseSql()
    sql = "SELECT path FROM app_distribution_platform_fileupload WHERE filename='{}'"
    try:
        bs.cursor.execute(sql.format(filename))
    except IntegrityError:
        pass
    bs.conn.commit()
    record = bs.cursor.fetchone()[0]
    bs.close()
    return record


def update_path(fname, path):
    name = 'caozhi'
    bs = BaseSql()
    sql = "UPDATE app_distribution_platform_fileupload SET path='{}' WHERE filename='{}';"
    # sql = "INSERT INTO app_distribution_platform_fileupload (username,filename,path) VALUES ('{}','{}','{}');"
    try:
        bs.cursor.execute(sql.format(name, fname, path))
    except IntegrityError:
        pass
    bs.conn.commit()
    bs.close()


def oss_file_pull(path=None):
    """
    将对象存储上的文件下拉到本地
    :return:
    """
    if not os.path.exists(settings.MEDIA_ROOT):
        os.makedirs(settings.MEDIA_ROOT)
    if path:
        print(settings.MEDIA_ROOT + '/' + path.split('/')[-1])
        urlretrieve(path, settings.MEDIA_ROOT + '/' + path.split('/')[-1])
    else:
        items = read_file()
        for item in items:
            if '.txt' not in item[1]:
                link = list(item[1])
                link[-3:] = 'txt'
                link = ''.join(link)
            else:
                link = item[1]
            urlretrieve(link, settings.MEDIA_ROOT + '/' + str(item[0]))


def delete_oss_file(fname):
    data = {
        'path': read_path(fname)
    }
    result = requests.post('http://172.18.55.20:30001/h5/delFile', headers=headers, data=data).json()
    return result


def save_oss_file(filename):
    with open('uploads/' + str(filename), 'r', encoding='utf-8') as f:
        file_data = f.read()
    data = {
        'filename': filename[:-4],
        'type': 'txt',
        'data': str(file_data),
        'oss_path': 'Python/wx273',
        'bucket': 'axh-static',
    }
    result = requests.post('http://172.18.55.20:30001/h5/fileUp', headers=headers, data=data).json()
    return result